package com.lry.basic.algorithm.recursion;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 全排列https://leetcode-cn.com/problems/permutations/solution/hui-su-suan-fa-python-dai-ma-java-dai-ma-by-liweiw/
 *
 */
public class Permute {

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        if(null==nums||nums.length==0)
            return ans;

        List<Integer> path = new ArrayList<>();
        boolean[] visited = new boolean[nums.length];
        dfs(visited,nums,path,ans);

        return ans;
    }

    private void dfs(boolean[] visited ,int[] nums, List<Integer> path, List<List<Integer>> ans) {

        if(path.size()==nums.length){
            ans.add(new ArrayList<>(path));
        }

        for(int i=0;i<nums.length;i++){
            if(!visited[i]){
                visited[i] = true;
                path.add(nums[i]);
                dfs(visited,nums,path,ans);
                visited[i] = false;
                path.remove(path.size()-1);
            }
        }

    }


    public List<List<Integer>> permute2(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        if(null==nums||nums.length==0)
            return ans;
        Arrays.sort(nums);
        List<Integer> path = new ArrayList<>();
        boolean[] visited = new boolean[nums.length];
        dfs2(visited,nums,path,ans);

        return ans;
    }

    private void dfs2(boolean[] visited ,int[] nums, List<Integer> path, List<List<Integer>> ans) {

        if(path.size()==nums.length){
            ans.add(new ArrayList<>(path));
        }

        for(int i=0;i<nums.length;i++){
            if(!visited[i]){
                if(i>0&&nums[i]==nums[i-1]&&!visited[i-1]){
                    continue;
                }
                visited[i] = true;
                path.add(nums[i]);
                dfs2(visited,nums,path,ans);
                visited[i] = false;
                path.remove(path.size()-1);
            }
        }

    }

    public static void main(String[] args) {
        System.out.println(new Permute().permute(new int[]{1, 2, 3}));
        System.out.println(new Permute().permute2(new int[]{1, 1}));
    }
}
